package com.hz.foodstalls.controller;

import java.io.File;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.hz.foodstalls.interceptor.AdminInterceptor;
import com.hz.foodstalls.model.Admin;
import com.hz.foodstalls.model.ComplaintAdvice;
import com.hz.foodstalls.model.RedbagLog;
import com.hz.foodstalls.model.Towns;
import com.hz.foodstalls.model.base.BaseComplaintAdvice;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.core.JFinal;
import com.jfinal.ext.render.excel.PoiRender;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.upload.UploadFile;

/**
 * ComplaintAdviceController, Generated by Robot on 2017-7-31 17:25:58.
 */
@Before(AdminInterceptor.class)
@ControllerBind(controllerKey = "/complaintadvice", viewPath = "/WEB-INF/views/complaintadvice/")
public class ComplaintAdviceController extends BaseController {
    public final String path = JFinal.me().getServletContext().getRealPath("/");
    private final String MODULE_NAME = "/complaintadvice";

    public void index() {
        String reservation = getPara("reservation");
        String starttime = null;
        String endtime = null;
        if (StringUtils.isNotBlank(reservation)) {
            String[] time = reservation.split(" - ");
            starttime = time[0];
            endtime = time[1] + " 23:59:59";
        }
        String username = getSessionAttr("username");
        Admin admin = Admin.dao.findFirst("select * from admin where username=?", username);
        String areaId = admin.getAreaId();
        String[] status = getParaValues("status");

        String statu = StringUtils.join(status, ",");
        if (areaId.isEmpty()) {
            Page<ComplaintAdvice> page = ComplaintAdvice.dao.page(getParaToInt("pageNumber", 1),
                    getParaToInt("pageSize", 10), getPara("advtype"), statu, getPara("degree"), starttime, endtime);
            setAttr("page", page);
        } else {
            Page<ComplaintAdvice> page = ComplaintAdvice.dao.page(getParaToInt("pageNumber", 1),
                    getParaToInt("pageSize", 10), getPara("advtype"), statu, getPara("degree"), starttime, endtime,
                    areaId);
            setAttr("page", page);
        }

        keepPara();
        setAttr("status", null == statu ? "" : statu);
        render("index.html");
    }

    @Clear
    public void save() {
        List<UploadFile> list = getFiles();
        ComplaintAdvice model = getModel(ComplaintAdvice.class, "");
        boolean isSave = model.getId() == null;

        if (ComplaintAdvice.dao.saveOrUpdate(model, isSave)) {
            Integer id = model.getId();
            for (UploadFile uf : list) {
                String dir = path + "/" + "uploadfile" + "/" + "pic" + "/" + id + "/";
                String url = "/" + "uploadfile" + "/" + "pic" + "/" + id + "/" + uf.getFileName();
                File fdir = new File(dir);
                File file = new File(path + url);
                if (!fdir.exists()) {
                    fdir.mkdirs();
                    uf.getFile().renameTo(file);
                } else {
                    uf.getFile().renameTo(file);
                }
                com.hz.foodstalls.model.UploadFile.dao.savepic(id.toString(), url, uf.getFileName());
            }
            render("submitSuccess.html");
        } else
            renderError(501);
    }

    @Clear
    // @Before(WxInterceptor.class)
    public void edit() {
        ComplaintAdvice complaintAdvice = new ComplaintAdvice();

        setAttr("complaintAdvice", complaintAdvice);
        render("edit.html");
    }

    public void delete() {
        String ids = StringUtils.join(getParaValues("ids"), ",");
        int ret = ComplaintAdvice.dao.batchDelete(ids);
        if (ret > 0) {
            ajaxJsonSuccessMessage("删除成功!");
        } else {
            ajaxJsonErrorMessage("删除失败！");
        }
    }

    public void view() {
        ComplaintAdvice complaintAdvice = ComplaintAdvice.dao.findById(getParaToInt("id", 0));
        List<ComplaintAdvice> list = ComplaintAdvice.dao.findUpload(getParaToInt("id", 0));
        setAttr("complaintAdvice", complaintAdvice);
        setAttr("list", list);
        render("view.html");
    }

    public void review() {
        int status = getParaToInt("status");
        int id = getParaToInt("id");
        int res = ComplaintAdvice.dao.statusUpdate(status, id);
        if (res > 0) {
            redirect(MODULE_NAME);
        } else {
            renderError(501);
        }
    }

    public void exportExcel() {
        // 查询得到list
        String advtype = getPara("advtype");
        String[] status = getParaValues("status");
        String statu = StringUtils.join(status, ",");
        String reservation = getPara("reservation");
        String degree = getPara("degree");
        String starttime = null;
        String endtime = null;
        if (StringUtils.isNotBlank(reservation)) {
            String[] time = reservation.split(" - ");
            starttime = time[0];
            endtime = time[1] + " 23:59:59";
        }
        String where = String.format("%s %s %s %s", StringUtils.isBlank(advtype) ? "1=1" : "adv_type='" + advtype + "'",
                StringUtils.isBlank(statu) ? "" : "and status in (" + statu + ")",
                StringUtils.isBlank(degree) ? "" : "and degree = '" + degree + "'",
                (starttime == "" && endtime == "") || (starttime == null && endtime == null) ? ""
                        : "and create_time between '" + starttime + "' and '" + endtime + "'");
        List list = ComplaintAdvice.dao.find("select * from complaint_advice where " + where + " order by id");
        PoiRender poi = PoiRender.me(list).headers(new String[] { "联系方式" }).sheetName("Sheet1").fileName("temp.xlsx")
                .headerRow(1).columns(new String[] { "phone" });
        // 写log表
        String type = getPara("type");
        if (!"0".equalsIgnoreCase(type)) {
            if (null != list && list.size() > 0) {
                RedbagLog log = new RedbagLog();
                log.setSearchParams((getRequest().getQueryString()));
                log.setLastAdvId(((BaseComplaintAdvice<ComplaintAdvice>) list.get(list.size() - 1)).getId());
                log.setTotal(list.size());
                log.setStatus(0);
                log.save();
            }
        }
        render(poi);
    }

    public void findTowns() {
        Map townsName = new HashMap<>();
        List towns = Towns.dao.find("select * from towns");
        for (int i = 0; i < towns.size(); i++) {
            int id = ((Towns) towns.get(i)).getId();
            String name = ((Towns) towns.get(i)).getName();
            townsName.put(id, name);
        }
        setAttr("townsName", townsName);
        renderJson();
    }

    public void assin() throws ParseException {
        String assintime = getPara("assintime");
        String seltowns = getPara("seltowns");
        String degree = getPara("degree");
        String id = getPara("id");
        int degrees = Integer.parseInt(degree);
        int ids = Integer.parseInt(id);
        if (assintime != null) {
            String workday = assintime + " 23:59:59";
            boolean b = ComplaintAdvice.dao.statusUpdate(ids, workday, seltowns, degrees);
            if (b == true) {
                ajaxJsonSuccessMessage("指派成功!");
            } else {
                ajaxJsonErrorMessage("处理失败！");
            }
        }
    }

    public void results() {
        String result = getPara("result");
        String id = getPara("id");
        int ids = Integer.parseInt(id);
        boolean b = ComplaintAdvice.dao.deal(ids, result);
        if (b == true) {
            ajaxJsonSuccessMessage("处理成功!");
        } else {
            ajaxJsonErrorMessage("处理失败！");
        }
    }

    private String indexTitle = "投诉与建议";
    private String editTitle = "处理";

    public Map<String, String> getPageTitleBread() {
        Map<String, String> pageTitleBread = new HashMap<String, String>();
        pageTitleBread.put("indexTitle", indexTitle);
        pageTitleBread.put("editTitle", editTitle);
        return pageTitleBread;
    }

}
